/*
 * Copyright (c) 2008, Solido Systems
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of Solido Systems nor the names of its contributors may be
 * used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.solidosystems.objectkitchen.test;

import com.solidosystems.objectkitchen.data.*;
import com.solidosystems.objectkitchen.storage.*;

import java.util.concurrent.*;
import java.util.*;
import java.io.*;
import java.sql.*;

public class Benchmark{
	private String folder;
	private BlockSet block;
	
	public Benchmark(String folder,int size){
		try{
			int poolsize=16;
			this.folder=folder;
			System.out.println("ObjectKitchen Benchmark v1");
			System.out.println(" + Preparing tests");
			Class.forName("org.postgresql.Driver");
			String dbURL = "jdbc:postgresql://127.0.0.1/perfdb?user=perftest&password=HWM";
			
			Connection dbCon = DriverManager.getConnection(dbURL);
			cleanTempFolder();
			block=new BlockSet(folder);
			ExecutorService exec=Executors.newFixedThreadPool(poolsize);
			System.out.println(" + Adding "+size+" documents");
			long pre=System.currentTimeMillis();
			for(int suba=0;suba<100;suba++){
				exec.submit(Executors.callable(new BenchmarkThread(dbCon,block,"thr-"+suba,size/100,BenchmarkThread.CREATE)));
			}
			exec.shutdown();
			while(!exec.isTerminated()){
				try{
					Thread.sleep(250);
				}catch(Exception e){}
			}
			long post=System.currentTimeMillis();
			long delta=post-pre;
			System.out.println("   - Total runtime "+((delta/100)/10.0)+" s");
			System.out.println("   - Average add time "+(delta/((float)size))+" ms");
			
			exec=Executors.newFixedThreadPool(poolsize);
			System.out.println(" + Reading "+size+" documents");
			pre=System.currentTimeMillis();
			for(int suba=0;suba<100;suba++){
				exec.submit(Executors.callable(new BenchmarkThread(dbCon,block,"thr-"+suba,size/100,BenchmarkThread.READ)));
			}
			exec.shutdown();
			while(!exec.isTerminated()){
				try{
					Thread.sleep(250);
				}catch(Exception e){}
			}
			post=System.currentTimeMillis();
			delta=post-pre;
			System.out.println("   - Total runtime "+((delta/100)/10.0)+" s");
			System.out.println("   - Average read time "+(delta/((float)size))+" ms");
			
			exec=Executors.newFixedThreadPool(poolsize);
			System.out.println(" + Update "+size+" documents");
			pre=System.currentTimeMillis();
			for(int suba=0;suba<100;suba++){
				exec.submit(Executors.callable(new BenchmarkThread(dbCon,block,"thr-"+suba,size/100,BenchmarkThread.UPDATE)));
			}
			exec.shutdown();
			while(!exec.isTerminated()){
				try{
					Thread.sleep(250);
				}catch(Exception e){}
			}
			post=System.currentTimeMillis();
			delta=post-pre;
			System.out.println("   - Total runtime "+((delta/100)/10.0)+" s");
			System.out.println("   - Average read time "+(delta/((float)size))+" ms");
			
			exec=Executors.newFixedThreadPool(poolsize);
			System.out.println(" + Scan "+size+" documents");
			pre=System.currentTimeMillis();
			for(int suba=0;suba<100;suba++){
				exec.submit(Executors.callable(new BenchmarkThread(dbCon,block,"thr-"+suba,size/100,BenchmarkThread.SCAN)));
			}
			exec.shutdown();
			while(!exec.isTerminated()){
				try{
					Thread.sleep(250);
				}catch(Exception e){}
			}
			post=System.currentTimeMillis();
			delta=post-pre;
			System.out.println("   - Total runtime "+((delta/100)/10.0)+" s");
			System.out.println("   - Average scan time "+(delta/((float)size))+" ms");
		
			/*
			exec=Executors.newFixedThreadPool(poolsize);
			System.out.println(" + Executing scripts on "+(size)+" documents");
			pre=System.currentTimeMillis();
			for(int suba=0;suba<100;suba++){
				exec.submit(Executors.callable(new BenchmarkThread(dbCon,block,"thr-"+suba,size/100,BenchmarkThread.SCRIPTUPDATE)));
			}
			exec.shutdown();
			while(!exec.isTerminated()){
				try{
					Thread.sleep(250);
				}catch(Exception e){}
			}
			post=System.currentTimeMillis();
			delta=post-pre;
			System.out.println("   - Total runtime "+((delta/100)/10.0)+" s");
			System.out.println("   - Average exec time "+(delta/((float)(size)))+" ms");
	
			exec=Executors.newFixedThreadPool(poolsize);
			System.out.println(" + Querying with scripts on "+(size)+" documents");
			pre=System.currentTimeMillis();
			for(int suba=0;suba<100;suba++){
				exec.submit(Executors.callable(new BenchmarkThread(dbCon,block,"thr-"+suba,size/100,BenchmarkThread.SCRIPTQUERY)));
			}
			exec.shutdown();
			while(!exec.isTerminated()){
				try{
					Thread.sleep(250);
				}catch(Exception e){}
			}
			post=System.currentTimeMillis();
			delta=post-pre;
			System.out.println("   - Total runtime "+((delta/100)/10.0)+" s");
			System.out.println("   - Average query time "+(delta/((float)(size)))+" ms");
		
			exec=Executors.newFixedThreadPool(poolsize);
			System.out.println(" + Attaching files to "+(size/10)+" documents");
			pre=System.currentTimeMillis();
			for(int suba=0;suba<100;suba++){
				exec.submit(Executors.callable(new BenchmarkThread(dbCon,block,"thr-"+suba,size/1000,BenchmarkThread.ATTACH)));
			}
			exec.shutdown();
			while(!exec.isTerminated()){
				try{
					Thread.sleep(250);
				}catch(Exception e){}
			}
			post=System.currentTimeMillis();
			delta=post-pre;
			System.out.println("   - Total runtime "+((delta/100)/10.0)+" s");
			System.out.println("   - Average attach time "+(delta/((float)(size/10)))+" ms");
			
			exec=Executors.newFixedThreadPool(poolsize);
			System.out.println(" + Reading attachments from "+(size/10)+" documents");
			pre=System.currentTimeMillis();
			for(int suba=0;suba<100;suba++){
				exec.submit(Executors.callable(new BenchmarkThread(dbCon,block,"thr-"+suba,size/1000,BenchmarkThread.READATTACH)));
			}
			exec.shutdown();
			while(!exec.isTerminated()){
				try{
					Thread.sleep(250);
				}catch(Exception e){}
			}
			post=System.currentTimeMillis();
			delta=post-pre;
			System.out.println("   - Total runtime "+((delta/100)/10.0)+" s");
			System.out.println("   - Average read time "+(delta/((float)(size/10)))+" ms");
			*/
			
			cleanTempFolder();
			
			System.out.println("Running single threaded JDBC tests");
			
			Statement st = dbCon.createStatement();
			try{
				st.executeUpdate("DROP table tbl_test1");
			}catch(Exception e){}
			st.executeUpdate("VACUUM FULL");
			st.executeUpdate("CREATE TABLE tbl_test1 (id VARCHAR PRIMARY KEY, grp VARCHAR, intval INT, strval1 VARCHAR,strval2 VARCHAR,strval3 VARCHAR,strval4 VARCHAR,tmodified TIMESTAMP,tcreated TIMESTAMP)");
			System.out.println(" + Adding "+(size)+" rows");
			exec=Executors.newFixedThreadPool(poolsize);
			pre=System.currentTimeMillis();

			for(int suba=0;suba<100;suba++){
				exec.submit(Executors.callable(new BenchmarkThread(dbCon,block,"thr-"+suba,size/100,BenchmarkThread.SQLADD)));
			}
			exec.shutdown();
			while(!exec.isTerminated()){
				try{
					Thread.sleep(250);
				}catch(Exception e){}
			}
			post=System.currentTimeMillis();
			delta=post-pre;
			System.out.println("   - Total runtime "+((delta/100)/10.0)+" s");
			System.out.println("   - Average add time "+(delta/((float)size))+" ms");
			
			st.executeUpdate("ANALYZE");
			
			System.out.println(" + Reading "+(size)+" rows");
			exec=Executors.newFixedThreadPool(poolsize);
			pre=System.currentTimeMillis();

			for(int suba=0;suba<100;suba++){
				exec.submit(Executors.callable(new BenchmarkThread(dbCon,block,"thr-"+suba,size/100,BenchmarkThread.SQLREAD)));
			}
			exec.shutdown();
			while(!exec.isTerminated()){
				try{
					Thread.sleep(250);
				}catch(Exception e){}
			}
			

			post=System.currentTimeMillis();
			delta=post-pre;
			System.out.println("   - Total runtime "+((delta/100)/10.0)+" s");
			System.out.println("   - Average read time "+(delta/((float)size))+" ms");
			
			System.out.println(" + Updating "+(size)+" rows");
			exec=Executors.newFixedThreadPool(poolsize);
			pre=System.currentTimeMillis();

			for(int suba=0;suba<100;suba++){
				exec.submit(Executors.callable(new BenchmarkThread(dbCon,block,"thr-"+suba,size/100,BenchmarkThread.SQLUPDATE)));
			}
			exec.shutdown();
			while(!exec.isTerminated()){
				try{
					Thread.sleep(250);
				}catch(Exception e){}
			}
			post=System.currentTimeMillis();
			delta=post-pre;
			System.out.println("   - Total runtime "+((delta/100)/10.0)+" s");
			System.out.println("   - Average read time "+(delta/((float)size))+" ms");
			
			System.out.println(" + Scan "+(size)+" rows");
			exec=Executors.newFixedThreadPool(poolsize);
			pre=System.currentTimeMillis();

			for(int suba=0;suba<100;suba++){
				exec.submit(Executors.callable(new BenchmarkThread(dbCon,block,"thr-"+suba,size/100,BenchmarkThread.SQLSCAN)));
			}
			exec.shutdown();
			while(!exec.isTerminated()){
				try{
					Thread.sleep(250);
				}catch(Exception e){}
			}
			post=System.currentTimeMillis();
			delta=post-pre;
			System.out.println("   - Total runtime "+((delta/100)/10.0)+" s");
			System.out.println("   - Average scan time "+(delta/((float)size))+" ms");
			
			st.close();
			dbCon.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private void deleteFolder(String folder) throws IOException{
		File ftest=new File(folder);
		String[] files=ftest.list();
		for(String file:files){
			if( file.equals(".svn") ) continue; // don't delete the svn folders :)
			ftest=new File(folder+file);
			if(ftest.isDirectory()){
				deleteFolder(folder+file+File.separator);
			}
			ftest.delete();
		}
	}

	public void cleanTempFolder(){
		try{
			File ftest=new File(folder);
			if(ftest.exists()){
				deleteFolder(folder);
			}
		}catch(Exception e){
			e.printStackTrace();
			System.exit(-1);
		}
	}
	
	public static void main(String args[]){
		try{
			if(args.length!=2){
				System.out.println("Usage: Benchmark <folder> <size>");
				System.exit(-1);
			}
			new Benchmark(args[0],Integer.parseInt(args[1]));
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}